<template>
  <div class="publish-container">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <button class="back-btn" @click="goBack">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
      <h2 class="nav-title">发布笔记</h2>
      <button class="publish-btn" @click="handlePublish" :disabled="publishing">
        {{ publishing ? '发布中...' : '发布' }}
      </button>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 标题输入 -->
      <div class="input-section">
        <input 
          v-model="formData.title" 
          type="text" 
          placeholder="请输入标题..."
          class="title-input"
          maxlength="50"
        />
        <div class="char-count">{{ formData.title.length }}/50</div>
      </div>

      <!-- 描述输入 -->
      <div class="input-section">
        <textarea 
          v-model="formData.description" 
          placeholder="记录你的生活瞬间..."
          class="description-textarea"
          rows="6"
          maxlength="500"
        ></textarea>
        <div class="char-count">{{ formData.description.length }}/500</div>
      </div>

      <!-- 媒体选择切换 -->
      <div class="media-type-selector">
        <button 
          :class="['media-type-btn', { active: mediaType === 'image' }]"
          @click="switchMediaType('image')"
        >
          📷 图片
        </button>
        <button 
          :class="['media-type-btn', { active: mediaType === 'video' }]"
          @click="switchMediaType('video')"
        >
          🎬 视频
        </button>
      </div>

      <!-- 图片上传区域 -->
      <div v-if="mediaType === 'image'" class="upload-section">
        <div class="section-title">添加图片（最多9张）</div>
        <div class="image-grid">
          <div 
            v-for="(image, index) in imageList" 
            :key="index" 
            class="image-item"
          >
            <img :src="image.preview" alt="预览图" />
            <button class="remove-btn" @click="removeImage(index)">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
                <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              </svg>
            </button>
          </div>
          <div v-if="imageList.length < 9" class="upload-btn" @click="triggerFileInput">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
              <path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
            <span>添加图片</span>
          </div>
        </div>
        <input 
          ref="fileInput" 
          type="file" 
          multiple 
          accept="image/*" 
          @change="handleFileSelect"
          style="display: none"
        />
      </div>

      <!-- 视频上传区域 -->
      <div v-if="mediaType === 'video'" class="upload-section">
        <div class="section-title">上传视频（最大500MB）</div>
        <div v-if="!videoFile" class="video-upload-area">
          <div class="upload-btn-large" @click="triggerVideoInput">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
              <path d="M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6z" stroke="currentColor" stroke-width="2"/>
              <path d="M14 2v6h6" stroke="currentColor" stroke-width="2"/>
            </svg>
            <p>点击选择视频</p>
            <small>支持 MP4, MOV, AVI, WEBM 格式</small>
          </div>
        </div>
        <div v-else class="video-preview-area">
          <video :src="videoPreview" controls class="video-preview"></video>
          <div class="video-info">
            <p>{{ videoFile.name }}</p>
            <p>{{ formatFileSize(videoFile.size) }}</p>
            <button @click="removeVideo" class="remove-video-btn">移除视频</button>
          </div>
          <div v-if="uploadProgress.show" class="upload-progress">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: uploadProgress.percentage + '%' }"></div>
            </div>
            <p>{{ uploadProgress.percentage }}% - {{ uploadProgress.speed }}</p>
          </div>
        </div>
        <input 
          ref="videoInput" 
          type="file" 
          accept="video/*" 
          @change="handleVideoSelect"
          style="display: none"
        />
      </div>

      <!-- 标签选择 -->
      <div class="tag-section">
        <div class="section-title">选择标签（最多5个）</div>
        <div class="tag-list">
          <button 
            v-for="tag in tags" 
            :key="tag.id"
            :class="['tag-btn', { 'selected': selectedTagIds.includes(tag.id) }]"
            @click="toggleTag(tag.id)"
            :disabled="!selectedTagIds.includes(tag.id) && selectedTagIds.length >= 5"
          >
            <img v-if="tag.icon" :src="tag.icon" class="tag-icon" />
            {{ tag.name }}
          </button>
        </div>
        <div class="char-count">已选择 {{ selectedTagIds.length }}/5 个标签</div>
      </div>
    </div>

    <!-- 加载提示 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { tagAPI } from '../api'

const router = useRouter()

// 响应式数据
const formData = ref({
  title: '',
  description: ''
})

const imageList = ref([])
const videoFile = ref(null)
const videoPreview = ref('')
const mediaType = ref('image') // 'image' or 'video'
const tags = ref([])
const selectedTagIds = ref([])
const loading = ref(false)
const publishing = ref(false)
const fileInput = ref(null)
const videoInput = ref(null)

// 视频上传进度
const uploadProgress = ref({
  show: false,
  percentage: 0,
  speed: '0 KB/s',
  sessionId: null
})

// 加载标签数据
const loadTags = async () => {
  try {
    loading.value = true
    const response = await tagAPI.getAllTags()
    if (response.data && Array.isArray(response.data)) {
      tags.value = response.data
    }
  } catch (error) {
    console.error('加载标签失败:', error)
    // 显示错误提示（可选）
  } finally {
    loading.value = false
  }
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)
  const remaining = 9 - imageList.value.length
  
  files.slice(0, remaining).forEach(file => {
    if (file.type.startsWith('image/')) {
      const reader = new FileReader()
      reader.onload = (e) => {
        imageList.value.push({
          file: file,
          preview: e.target.result
        })
      }
      reader.readAsDataURL(file)
    }
  })
}

// 移除图片
const removeImage = (index) => {
  imageList.value.splice(index, 1)
}

// 切换媒体类型
const switchMediaType = (type) => {
  mediaType.value = type
  if (type === 'image') {
    videoFile.value = null
    videoPreview.value = ''
  } else {
    imageList.value = []
  }
}

// 触发视频选择
const triggerVideoInput = () => {
  videoInput.value?.click()
}

// 处理视频选择
const handleVideoSelect = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return
  
  // 检查文件大小（500MB限制）
  if (file.size > 500 * 1024 * 1024) {
    alert('视频文件大小不能超过500MB')
    return
  }
  
  // 检查文件类型
  if (!file.type.startsWith('video/')) {
    alert('请选择视频文件')
    return
  }
  
  videoFile.value = file
  
  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    videoPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 移除视频
const removeVideo = () => {
  videoFile.value = null
  videoPreview.value = ''
  if (videoInput.value) {
    videoInput.value.value = ''
  }
  uploadProgress.value = {
    show: false,
    percentage: 0,
    speed: '0 KB/s',
    sessionId: null
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

// 视频分片上传
const uploadVideoChunks = async () => {
  const chunkSize = 5 * 1024 * 1024 // 5MB
  const chunkCount = Math.ceil(videoFile.value.size / chunkSize)
  
  const token = localStorage.getItem('token')
  if (!token) {
    alert('请先登录')
    router.push('/login')
    return
  }
  
  try {
    uploadProgress.value.show = true
    uploadProgress.value.percentage = 0
    
    // 1. 初始化上传会话
    const initFormData = new FormData()
    initFormData.append('filename', videoFile.value.name)
    initFormData.append('file_size', videoFile.value.size)
    initFormData.append('content_type', videoFile.value.type)
    
    const initResponse = await fetch('http://localhost:8000/api/content/upload/init', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: initFormData
    })
    
    const initResult = await initResponse.json()
    if (!initResult.success) {
      throw new Error(initResult.message)
    }
    
    const { session_id } = initResult
    uploadProgress.value.sessionId = session_id
    
    // 2. 上传分片
    const startTime = Date.now()
    let uploadedBytes = 0
    
    for (let i = 0; i < chunkCount; i++) {
      const start = i * chunkSize
      const end = Math.min(start + chunkSize, videoFile.value.size)
      const chunk = videoFile.value.slice(start, end)
      
      const chunkFormData = new FormData()
      chunkFormData.append('session_id', session_id)
      chunkFormData.append('chunk_number', i.toString())
      chunkFormData.append('chunk_data', chunk, `chunk_${i}`)
      
      await fetch('http://localhost:8000/api/content/upload/chunk', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: chunkFormData
      })
      
      uploadedBytes += end - start
      
      // 更新进度
      const elapsed = (Date.now() - startTime) / 1000
      const speed = uploadedBytes / elapsed
      const speedStr = formatFileSize(speed) + '/s'
      
      uploadProgress.value.percentage = Math.round((uploadedBytes / videoFile.value.size) * 100)
      uploadProgress.value.speed = speedStr
      
      console.log(`上传进度: ${uploadProgress.value.percentage}%`)
    }
    
    // 3. 完成上传
    const finishFormData = new FormData()
    finishFormData.append('session_id', session_id)
    finishFormData.append('title', formData.value.title)
    finishFormData.append('description', formData.value.description || '')
    finishFormData.append('tag_ids', JSON.stringify(selectedTagIds.value))
    finishFormData.append('status', '2')
    
    const finishResponse = await fetch('http://localhost:8000/api/content/upload/finish', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: finishFormData
    })
    
    const finishResult = await finishResponse.json()
    
    if (finishResult.success) {
      alert('视频发布成功！')
      router.push('/home')
    } else {
      alert(`发布失败: ${finishResult.message}`)
    }
    
  } catch (error) {
    console.error('视频上传失败:', error)
    alert('视频上传失败，请稍后重试')
  } finally {
    uploadProgress.value.show = false
    publishing.value = false
  }
}

// 切换标签选择
const toggleTag = (tagId) => {
  const index = selectedTagIds.value.indexOf(tagId)
  if (index > -1) {
    selectedTagIds.value.splice(index, 1)
  } else if (selectedTagIds.value.length < 5) {
    selectedTagIds.value.push(tagId)
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 发布内容
const handlePublish = async () => {
  // 验证标题
  if (!formData.value.title.trim()) {
    alert('请输入标题')
    return
  }

  // 验证媒体
  if (mediaType.value === 'image' && imageList.value.length === 0) {
    alert('请至少上传一张图片')
    return
  }

  if (mediaType.value === 'video' && !videoFile.value) {
    alert('请上传视频')
    return
  }

  // 验证标签
  if (selectedTagIds.value.length === 0) {
    alert('请至少选择一个标签')
    return
  }

  // 如果是视频，使用分片上传
  if (mediaType.value === 'video') {
    try {
      publishing.value = true
      await uploadVideoChunks()
    } finally {
      publishing.value = false
    }
    return
  }

  try {
    publishing.value = true

    // 构建FormData
    const formDataToSend = new FormData()
    formDataToSend.append('title', formData.value.title)
    formDataToSend.append('description', formData.value.description || '')
    formDataToSend.append('tag_ids', JSON.stringify(selectedTagIds.value))
    formDataToSend.append('status', '2') // 已发布

    // 添加图片
    imageList.value.forEach((imageItem, index) => {
      formDataToSend.append('files', imageItem.file)
    })

    // 获取token
    const token = localStorage.getItem('token')
    if (!token) {
      alert('请先登录')
      router.push('/login')
      return
    }

    // 发送请求
    const response = await fetch('http://localhost:8000/api/content/publish', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: formDataToSend
    })

    const result = await response.json()

    if (result.success) {
      alert('发布成功！')
      // 返回首页
      router.push('/home')
    } else {
      alert(`发布失败: ${result.message}`)
    }

  } catch (error) {
    console.error('发布失败:', error)
    alert('发布失败，请稍后重试')
  } finally {
    publishing.value = false
  }
}

// 组件挂载时加载标签
onMounted(() => {
  loadTags()
})
</script>

<style scoped>
.publish-container {
  width: 100%;
  min-height: 100vh;
  background: #ffffff;
}

.top-nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 56px;
  background: #fff;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.back-btn {
  background: transparent;
  border: none;
  padding: 8px;
  cursor: pointer;
  color: #333;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.publish-btn {
  background: #ff2442;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}

.publish-btn:hover:not(:disabled) {
  background: #ff4569;
}

.publish-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.content-area {
  margin-top: 56px;
  padding: 20px;
  padding-bottom: 80px;
}

.input-section {
  margin-bottom: 24px;
}

.title-input {
  width: 100%;
  border: none;
  border-bottom: 1px solid #e9ecef;
  padding: 12px 0;
  font-size: 18px;
  font-weight: 500;
  outline: none;
}

.title-input:focus {
  border-bottom-color: #ff2442;
}

.description-textarea {
  width: 100%;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 12px;
  font-size: 15px;
  resize: none;
  outline: none;
  font-family: inherit;
}

.description-textarea:focus {
  border-color: #ff2442;
}

.char-count {
  text-align: right;
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.upload-section, .tag-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

/* 媒体类型选择器 */
.media-type-selector {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.media-type-btn {
  flex: 1;
  padding: 12px 24px;
  border: 2px solid #e9ecef;
  background: #fff;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.media-type-btn.active {
  border-color: #ff2442;
  background: #fff5f6;
  color: #ff2442;
}

/* 视频上传区域 */
.upload-btn-large {
  width: 100%;
  min-height: 200px;
  border: 2px dashed #d0d0d0;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.upload-btn-large:hover {
  border-color: #ff2442;
  background: #fff5f6;
}

.upload-btn-large svg {
  margin-bottom: 12px;
  color: #666;
}

.upload-btn-large p {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.upload-btn-large small {
  font-size: 12px;
  color: #999;
}

/* 视频预览区域 */
.video-preview-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.video-preview {
  width: 100%;
  max-height: 400px;
  border-radius: 8px;
  background: #000;
}

.video-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.video-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.remove-video-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  color: #ff2442;
}

.remove-video-btn:hover {
  border-color: #ff2442;
}

/* 上传进度条 */
.upload-progress {
  margin-top: 12px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-fill {
  height: 100%;
  background: #ff2442;
  transition: width 0.3s;
}

.upload-progress p {
  margin: 0;
  font-size: 12px;
  color: #666;
  text-align: center;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 28px;
  height: 28px;
  background: rgba(0, 0, 0, 0.6);
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-btn {
  aspect-ratio: 1;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.2s;
  color: #999;
}

.upload-btn:hover {
  border-color: #ff2442;
  color: #ff2442;
}

.upload-btn span {
  margin-top: 8px;
  font-size: 12px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border: 1px solid #e9ecef;
  border-radius: 20px;
  background: #fff;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.tag-btn:hover:not(:disabled) {
  border-color: #ff2442;
  color: #ff2442;
}

.tag-btn.selected {
  background: #ff2442;
  color: white;
  border-color: #ff2442;
}

.tag-btn:disabled:not(.selected) {
  opacity: 0.5;
  cursor: not-allowed;
}

.tag-icon {
  width: 16px;
  height: 16px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-overlay p {
  color: white;
  margin-top: 16px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>

